package controllers

import (
	"book/cache"
	"book/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Add() {
	title := c.GetString("title")
	tv := c.GetString("tv")
	name := c.GetString("name")
	look, _ := c.GetInt("look")
	score := c.GetString("score")

	book := models.Book{
		Title: title,
		Tv:    tv,
		Name:  name,
		Look:  look,
		Score: score,
	}
	err := models.DB.Debug().Create(&book).Error
	if book.Title == "" || book.Tv == "" || book.Name == "" || book.Look == 0 || book.Score == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}

	jsonData, _ := json.Marshal(&book)
	cache.Rdb.Set(cache.Ctx, "book-add", jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *BookController) List() {
	var allbook []models.Book

	err := models.DB.Debug().Find(&allbook).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "展示失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	}

	//jsonData, _ := json.Marshal(&allbook)
	//cache.Rdb.Set(cache.Ctx, "book-add", jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "展示成功",
		"data": allbook,
	}
	c.ServeJSON()
	return
}
func (c *BookController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	tv := c.GetString("tv")
	name := c.GetString("name")
	look, _ := c.GetInt("look")
	score := c.GetString("score")

	book := models.Book{
		Title: title,
		Tv:    tv,
		Name:  name,
		Look:  look,
		Score: score,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&book).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *BookController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Book{}, id).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
